package com.github.yangyishe.p200;

import java.util.HashSet;
import java.util.Set;

public class Problem128_b {
    public static void main(String[] args) {
        int[] nums={100,4,200,1,3,2};

        System.out.println(new Problem128_b().longestConsecutive(nums));
    }

    public int longestConsecutive(int[] nums) {
        // 创建num_set方便快速搜索
        Set<Integer> numSet=new HashSet<>();
        for (int num : nums) {
            numSet.add(num);
        }

        // 外层循环，遇到前一个数字不存在的情况，寻找最大长度；如果前一个数字存在，则跳过不需要寻找
        int currentStreak=0;
        int longestStreak=0;
        int tempNum;
        for (int num : numSet) {
            if(numSet.contains(num-1)){
                continue;
            }
            currentStreak=1;
            tempNum=num;
            while(true){
                tempNum+=1;
                if(numSet.contains(tempNum)){
                    currentStreak++;
                }else{
                    break;
                }
            }
            longestStreak=Math.max(longestStreak,currentStreak);

        }

        return longestStreak;
    }
}
